<template>
  <div class="j_box1">
    <div class="device-layout">
      <!-- 左侧客户列表树形控件 -->
      <div class="tree-container">
        <div class="tree-header">
          <h3>客户列表</h3>
          <el-button type="primary" size="small" @click="handleAddCustomer">
            <el-icon>
              <Plus />
            </el-icon>
            新增客户
          </el-button>
        </div>

        <div>
          <el-input v-model="filterText" placeholder="搜索客户名称" clearable size="small">
            <template #prefix>
              <el-icon>
                <Search />
              </el-icon>
            </template>
          </el-input>
          <el-tree
            ref="treeRef"
            style="height: 740px; padding-top: 10px; margin-top: 10px"
            :data="customerTreeData"
            :filter-node-method="filterNode"
            :props="treeProps"
            node-key="id"
            :default-expand-all="true"
            :expand-on-click-node="false"
            :highlight-current="true"
            class="device-tree"
            @node-click="handleNodeClick"
          >
            <template #default="{ node, data }">
              <span class="tree-node">
                <el-icon class="tree-icon">
                  <UserFilled />
                </el-icon>
                <span class="tree-label">{{ data.name }}</span>
                <span class="tree-count">{{ data.deviceCount || "01" }}</span>
              </span>
            </template>
          </el-tree>
        </div>
      </div>
      <div class="dev-list">
        <div style="padding: 15px">
          <el-input v-model="filterText" placeholder="搜索客户名称" clearable size="small">
            <template #prefix>
              <el-icon>
                <Search />
              </el-icon>
            </template>
          </el-input>
        </div>
        <el-scrollbar style="height: 780px">
          <div v-for="item in devList" :key="item.id" style="padding: 0 10px; margin-bottom: 10px">
            <div
              v-if="item?.device?.useStatus == 1 && item?.locus?.stay == '行驶'"
              :class="selectedDeviceId == item.id ? 'cheBoxSelect' : 'cheBox'"
            >
              <div
                style="display: flex; margin-left: 10px; width: 100%; align-items: center"
                @click="devClickEvent(item)"
              >
                <el-image
                  :src="'/src/assets/img/01.png'"
                  alt="客户图片"
                  style="width: 45px; height: auto"
                />
                <div style="margin-left: 5px; width: 100%">
                  <div style="color: #228b22; display: flex">
                    <span style="font-size: 12px; flex: 1">{{ item.carNumber }}</span>
                    <span style="font-size: 12px; margin-right: 10px">
                      {{ item.locus.speed }}km/h
                    </span>
                  </div>
                  <div style="display: flex; align-items: center; margin-top: 5px">
                    <el-image
                      :src="'/src/assets/img/04.png'"
                      alt="客户图片"
                      style="width: 15px; height: auto"
                    />
                    <el-image
                      :src="'/src/assets/img/05.png'"
                      alt="客户图片"
                      style="width: 15px; height: auto; margin-left: 10px"
                    />
                  </div>
                </div>
              </div>
              <div
                style="height: 1px; background-color: #e4e7ed; width: 100%; margin-top: 10px"
              ></div>
              <div style="text-align: center; margin-top: 10px">
                <el-button size="small" plain @click="trajectoryEvent(item)">轨迹回放</el-button>
                <el-button size="small" plain>实时跟踪</el-button>
              </div>
            </div>
            <div
              v-if="item?.device?.useStatus == 1 && item?.locus?.stay == '停留'"
              :class="selectedDeviceId == item.id ? 'cheBoxSelect' : 'cheBox'"
            >
              <div
                style="display: flex; margin-left: 10px; width: 100%; align-items: center"
                @click="devClickEvent(item)"
              >
                <el-image
                  :src="'/src/assets/img/02.png'"
                  alt="客户图片"
                  style="width: 45px; height: auto"
                />
                <div style="margin-left: 5px; width: 100%">
                  <div style="color: #b22222; display: flex; align-items: center">
                    <span style="font-size: 12px; flex: 1">{{ item.carNumber }}</span>
                    <span style="font-size: 12px; margin-right: 10px">
                      静止
                      <p v-if="item.locus.stayDuration != 0">{{ item.locus.stayDuration }}</p>
                    </span>
                  </div>
                  <div style="display: flex; align-items: center; margin-top: 5px">
                    <el-image
                      :src="'/src/assets/img/04.png'"
                      alt="客户图片"
                      style="width: 15px; height: auto"
                    />
                    <el-image
                      :src="'/src/assets/img/05.png'"
                      alt="客户图片"
                      style="width: 15px; height: auto; margin-left: 10px"
                    />
                  </div>
                </div>
              </div>
              <div
                style="height: 1px; background-color: #e4e7ed; width: 100%; margin-top: 10px"
              ></div>
              <div style="text-align: center; margin-top: 10px">
                <el-button size="small" plain @click="trajectoryEvent(item)">轨迹回放</el-button>
                <el-button size="small" plain>实时跟踪</el-button>
              </div>
            </div>
            <div
              v-if="item?.device?.useStatus == 0"
              :class="selectedDeviceId == item.id ? 'cheBoxSelect' : 'cheBox'"
            >
              <div
                style="display: flex; margin-left: 10px; width: 100%; align-items: center"
                @click="devClickEvent(item)"
              >
                <el-image
                  :src="'/src/assets/img/03.png'"
                  alt="客户图片"
                  style="width: 45px; height: auto"
                />
                <div style="margin-left: 5px; width: 100%">
                  <div style="color: #808080; display: flex">
                    <span style="font-size: 12px; flex: 1">{{ item.carNumber }}</span>
                    <span style="font-size: 12px; margin-right: 10px">离线</span>
                  </div>
                  <div style="display: flex; align-items: center; margin-top: 5px">
                    <el-image
                      :src="'/src/assets/img/04.png'"
                      alt="客户图片"
                      style="width: 15px; height: auto"
                    />
                    <el-image
                      :src="'/src/assets/img/05.png'"
                      alt="客户图片"
                      style="width: 15px; height: auto; margin-left: 10px"
                    />
                  </div>
                </div>
              </div>
              <div
                style="height: 1px; background-color: #e4e7ed; width: 100%; margin-top: 10px"
              ></div>
              <div style="text-align: center; margin-top: 10px">
                <el-button size="small" plain @click="trajectoryEvent(item)">轨迹回放</el-button>
                <el-button size="small" plain>实时跟踪</el-button>
              </div>
            </div>
          </div>
        </el-scrollbar>
      </div>
      <!-- 右侧内容区域 - 百度地图 -->
      <div class="content-container">
        <div v-if="chePostions" class="posBox">{{ chePostions }}</div>
        <div class="djs">
          <span style="color: #228b22; font-weight: 600">{{ timing }}</span>
          <span style="margin-left: 3px">秒</span>
        </div>
        <div id="baiduMap" class="baidu-map"></div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import deviceIcon from "@/assets/img/07.png";
import { ref, onMounted, nextTick, onBeforeUnmount, watch } from "vue";
import type { ElTree, FilterNodeMethodFunction, TreeInstance } from "element-plus";
import { Plus, UserFilled } from "@element-plus/icons-vue";
import UserAPI from "@/api/system/user.api";
import MonitorAPI from "@/api/system/monitor.api";
import { useRouter } from "vue-router";
// 树形控件引用
const treeRef = ref<InstanceType<typeof ElTree>>();
const postions = ref([]);
// 树形控件配置
const treeProps = {
  children: "children",
  label: "name",
};
const timing = ref(20);
const chePostions = ref("");
const selectedDeviceId = ref(null);
const filterText = ref("");

// 20秒倒计时：timing.value 每秒减1直到为0
// const timing = ref(20);
let countdownTimer: number | null = null;

onMounted(() => {
  if (countdownTimer) {
    clearInterval(countdownTimer as any);
  }
  countdownTimer = window.setInterval(() => {
    if (timing.value > 0) {
      timing.value -= 1;
    } else {
      // 倒计时到0：重置为20并刷新数据（不清除选中设备）
      timing.value = 20;
      getCustomerList();
      getDevList();
    }
  }, 1000);
});

onBeforeUnmount(() => {
  if (countdownTimer) {
    clearInterval(countdownTimer as any);
    countdownTimer = null;
  }
});
watch(filterText, (val) => {
  treeRef.value!.filter(val);
});
const filterNode: FilterNodeMethodFunction = (value, data) => {
  if (!value) return true;
  console.log(value, data);
  return (data.name || "").indexOf(value) !== -1;
};

// 获取路由实例
const router = useRouter();

function trajectoryEvent(item) {
  // 跳转到轨迹地图页面，携带设备ID参数
  router.push({
    path: "/map",
    query: {
      id: item.id,
    },
  });
}

// 客户树形数据
const customerTreeData = ref([]);
// 设备列表
const devList = ref([]);
const devListParamet = ref({
  userId: 1,
  clientName: "",
  cardId: "",
  pageNum: 1,
  pageSize: 9999,
  isLower: true,
});
// 处理节点点击
const handleNodeClick = (data: any) => {
  console.log("选中客户:", data);
};

// 处理新增客户
const handleAddCustomer = () => {
  console.log("新增客户");
};

// const devClickEvent = (item: any) => {
//   console.log(item)

//   if (selectedDeviceId.value == item.id) {
//     selectedDeviceId.value = null
//   } else {
//     selectedDeviceId.value = item.id
//   }
//   console.log('selectedDeviceId', selectedDeviceId.value)
// }

// 获取客户列表数据
const getCustomerList = async () => {
  try {
    const { data } = await UserAPI.getTreeInfo();
    customerTreeData.value = data.data;
  } catch (error) {
    console.error("获取客户列表失败:", error);
  }
};

// 获取设备列表
const getDevList = async () => {
  try {
    const { data } = await UserAPI.pageList(devListParamet.value);
    devList.value = data.data.records;
    console.log("设备列表", devList.value);
    if (selectedDeviceId.value) {
      devList.value.forEach((item: any) => {
        if (item.id == selectedDeviceId.value) {
          // chePostions.value = item.position
          getDevMap(item);
          updateSelectedMarker(item);
        }
      });
    }
  } catch (error) {
    console.error("获取设备列表失败:", error);
  }
};

// 百度地图相关
let map: any = null;
let markers: any[] = []; // 存储所有标注点

// // 创建自定义图标标注
// const createCustomMarker = (
//   lng: number,
//   lat: number,
//   iconUrl: string,
//   title: string = "",
//   content: string = ""
// ) => {
//   if (!map) return;

//   // 创建坐标点
//   const point = new (window as any).BMapGL.Point(lng, lat);

//   // 创建自定义图标
//   const icon = new (window as any).BMapGL.Icon(
//     iconUrl, // 图标地址
//     new (window as any).BMapGL.Size(32, 32), // 图标尺寸
//     {
//       anchor: new (window as any).BMapGL.Size(16, 32), // 图标的定位锚点
//       imageOffset: new (window as any).BMapGL.Size(0, 0), // 图标所用的图片的偏移值
//     }
//   );

//   // 创建标注
//   const marker = new (window as any).BMapGL.Marker(point, { icon });

//   // 添加到地图
//   map.addOverlay(marker);

//   // 如果有标题或内容，添加信息窗口
//   if (title || content) {
//     const infoWindow = new (window as any).BMapGL.InfoWindow(
//       `<div style="padding: 10px;">
//         <h4 style="margin: 0 0 8px 0; color: #333;">${title}</h4>
//         <p style="margin: 0; color: #666;">${content}</p>
//       </div>`,
//       {
//         width: 200,
//         height: 100,
//       }
//     );

//     // 点击标注显示信息窗口
//     marker.addEventListener("click", () => {
//       map.openInfoWindow(infoWindow, point);
//     });
//   }

//   // 存储标注引用
//   markers.push(marker);

//   return marker;
// };

// 清除所有标注
const clearAllMarkers = () => {
  if (!map) return;

  markers.forEach((marker) => {
    map.removeOverlay(marker);
  });
  markers = [];
};

// 添加单个标注点（可供外部调用）
const addMarker = (
  lng: number,
  lat: number,
  options: {
    iconUrl?: string;
    title?: string;
    content?: string;
    iconSize?: { width: number; height: number };
  } = {}
) => {
  const {
    iconUrl = "/src/assets/images/default-marker.png",
    title = "",
    content = "",
    iconSize = { width: 32, height: 32 },
  } = options;

  return createCustomMarker(lng, lat, iconUrl, title, content);
};

// 初始化百度地图
// 修改 initBaiduMap 函数
const initBaiduMap = () => {
  nextTick(() => {
    const mapContainer = document.getElementById("baiduMap");
    if (!mapContainer) {
      console.error("地图容器未找到");
      return;
    }

    try {
      // 创建地图实例 - 使用BMapGL
      map = new (window as any).BMapGL.Map("baiduMap");

      // 设置地图中心点和缩放级别
      const point = new (window as any).BMapGL.Point(116.404, 39.915); // 北京坐标
      map.centerAndZoom(point, 15);

      // 启用滚轮缩放
      map.enableScrollWheelZoom(true);

      // 添加地图控件
      map.addControl(new (window as any).BMapGL.NavigationControl());
      map.addControl(new (window as any).BMapGL.ScaleControl());
      // 注意：BMapGL中OverviewMapControl可能不可用，暂时移除
      // map.addControl(new (window as any).BMapGL.OverviewMapControl());

      console.log("百度地图初始化完成", map);

      // 初始化设备标注
      // createDeviceMarkers();
    } catch (error) {
      console.error("百度地图初始化失败:", error);
    }
  });
};

// 修改 onMounted 钩子
onMounted(() => {
  getCustomerList();
  getDevList();

  // 延迟初始化百度地图，确保DOM完全加载
  setTimeout(() => {
    if (typeof (window as any).BMapGL !== "undefined") {
      console.log("百度地图GL API已加载");
      initBaiduMap();
    } else {
      console.log("等待百度地图GL API加载...");
      // 如果百度地图API还未加载完成，等待加载
      const checkBMap = setInterval(() => {
        if (typeof (window as any).BMapGL !== "undefined") {
          console.log("百度地图GL API加载完成");
          clearInterval(checkBMap);
          initBaiduMap();
        }
      }, 100);

      // 设置超时，避免无限等待
      setTimeout(() => {
        clearInterval(checkBMap);
        console.error("百度地图GL API加载超时");
      }, 10000);
    }
  }, 500);
});

// 添加：根据选中设备刷新地图标注与信息窗口
const updateSelectedMarker = (item: any) => {
  if (!map) return;
  // 清理旧标注
  clearAllMarkers();

  // 更新顶部位置展示
  chePostions.value = item.locus?.position || "";

  // 创建新坐标点
  const point = new (window as any).BMapGL.Point(
    parseFloat(item.locus?.lng),
    parseFloat(item.locus?.lat)
  );

  // 保持当前缩放级别，移动到新位置
  const currentZoom = map.getZoom && map.getZoom();
  map.centerAndZoom(point, currentZoom || 18);

  // 创建标注
  const icon = new (window as any).BMapGL.Icon(deviceIcon, new (window as any).BMapGL.Size(32, 32));
  const marker = new (window as any).BMapGL.Marker(point, { icon });
  map.addOverlay(marker);
  markers.push(marker);

  // 三种信息窗口
  const infoWindow = new (window as any).BMapGL.InfoWindow(
    `<div style="padding: 10px;">
      <div style="display: flex; align-items: center; margin-bottom: 8px;">
        <h4 style="margin: 0; color: #333;">${item.deviceName || "设备"}</h4>
        <p style="margin: 0 0 0 8px; color: #999;">(离线)</p>
      </div>
      <p style="margin: 0; color: #666;">IMEI: ${item.deviceNumber || "N/A"}</p>
      <p style="margin: 4px 0 0 0; color: #666;">速度: ${item.speed || "0"}km/h</p>
      <p style="margin: 4px 0 0 0; color: #666;">定位时间: ${item.createTime || "0"}( ${item.orientation || "暂无"})</p>
      <p style="margin: 4px 0 0 0; color: #666;">电源: ${item.battery == 0 ? "开启" : "关闭"}km/h</p>
      <p style="margin: 4px 0 0 0; color: #666;">总里程: ${item.mileage || "0"}km</p>
    </div>`,
    { width: 300, height: 220 }
  );
  const infoWindow1 = new (window as any).BMapGL.InfoWindow(
    `<div style="padding: 10px;">
      <div style="display: flex; align-items: center; margin-bottom: 8px;">
        <h4 style="margin: 0; color: #333;">${item.deviceName || "设备"}</h4>
        <p style="margin: 0 0 0 8px; color: #228b22;">${item.locus?.speed}</p>
      </div>
      <p style="margin: 0; color: #666;">IMEI: ${item.deviceNumber || "N/A"}</p>
      <p style="margin: 4px 0 0 0; color: #666;">速度: ${item.speed || "0"}km/h</p>
      <p style="margin: 4px 0 0 0; color: #666;">定位时间: ${item.createTime || "0"}( ${item.orientation || "暂无"})</p>
      <p style="margin: 4px 0 0 0; color: #666;">电源: ${item.battery == 0 ? "开启" : "关闭"}km/h</p>
      <p style="margin: 4px 0 0 0; color: #666;">总里程: ${item.mileage || "0"}km</p>
    </div>`,
    { width: 300, height: 220 }
  );
  const infoWindow2 = new (window as any).BMapGL.InfoWindow(
    `<div style="padding: 10px;">
      <div style="display: flex; align-items: center; margin-bottom: 8px;">
        <h4 style="margin: 0; color: #333;">${item.deviceName || "设备"}</h4>
        <p style="margin: 0 0 0 8px; color: #B22222;">${item.locus.stayDuration}</p>
      </div>
      <p style="margin: 0; color: #666;">IMEI: ${item.deviceNumber || "N/A"}</p>
      <p style="margin: 4px 0 0 0; color: #666;">速度: ${item.locus.speed || "0"}km/h</p>
      <p style="margin: 4px 0 0 0; color: #666;">定位时间: ${item.locus.createTime || "0"}( ${item.locus.orientation || "暂无"})</p>
      <p style="margin: 4px 0 0 0; color: #666;">电源: ${item.locus.battery == 0 ? "开启" : "关闭"}</p>
      <p style="margin: 4px 0 0 0; color: #666;">总里程: ${item.locus.mileage || "0"}km</p>
    </div>`,
    { width: 300, height: 220 }
  );

  // 打开对应信息窗口
  if (item.device.useStatus == 0) {
    map.openInfoWindow(infoWindow, point);
  } else if (item.device.useStatus == 1 && item.locus?.stay == "行驶") {
    map.openInfoWindow(infoWindow1, point);
  } else if (item.device.useStatus == 1 && item.locus?.stay == "停留") {
    map.openInfoWindow(infoWindow2, point);
  }
};
// 设备点击事件 - 定位到地图标注
const devClickEvent = (item: any) => {
  // 设置选中状态
  console.log("item", item);

  // 先清除所有现有标注和信息窗口
  clearAllMarkers();
  if (map) {
    map.closeInfoWindow();
  }

  if (selectedDeviceId.value == item.id) {
    // 如果点击的是已选中的设备，则取消选中
    selectedDeviceId.value = null;
    chePostions.value = "";
  } else {
    // 选中新设备
    selectedDeviceId.value = item.id;
    chePostions.value = item.locus?.position;
    getDevMap(item);
    // 如果设备有坐标，定位到地图上
  }
};

function getDevMap(item) {
  console.log("地图", item);

  if (item.locus?.lng && item.locus?.lat && map) {
    const point = new (window as any).BMapGL.Point(
      parseFloat(item.locus?.lng),
      parseFloat(item.locus.lat)
    );
    map.centerAndZoom(point, 18); // 放大到18级

    const icon = new (window as any).BMapGL.Icon(
      deviceIcon,
      new (window as any).BMapGL.Size(32, 32)
    );
    const marker = new (window as any).BMapGL.Marker(point, { icon });
    map.addOverlay(marker);

    // 将新标注添加到markers数组中
    markers.push(marker);

    // 创建设备信息窗口
    const infoWindow = new (window as any).BMapGL.InfoWindow(
      `<div style="padding: 10px;">
        <div style="display: flex; align-items: center; margin-bottom: 8px;">
          <h4 style="margin: 0; color: #333;">${item.carNumber || "设备"}</h4>
          <p style="margin: 0 0 0 8px; color: #999;">(离线)</p>
        </div>
        <p style="margin: 0; color: #666;">IMEI: ${item.device.deviceNumber || "N/A"}</p>
        <p style="margin: 4px 0 0 0; color: #666;">速度: ${item.locus.speed || "0"}km/h</p>
        <p style="margin: 4px 0 0 0; color: #666;">定位时间: ${item.device.lastTime || "0"}( ${item.locus.orientation || "暂无"})</p>
        <p style="margin: 4px 0 0 0; color: #666;">电源: ${item.locus.battery == "开" ? "开启" : "关闭"}km/h</p>
        <p style="margin: 4px 0 0 0; color: #666;">总里程: ${item.locus.mileage || "0"}km</p>
      </div>`,
      { width: 300, height: 220 }
    );
    const infoWindow1 = new (window as any).BMapGL.InfoWindow(
      `<div style="padding: 10px;">
        <div style="display: flex; align-items: center; margin-bottom: 8px;">
          <h4 style="margin: 0; color: #333;">${item.carNumber || "设备"}</h4>
          <p style="margin: 0 0 0 8px; color: #228b22;">${item.locus?.speed}</p>
        </div>
        <p style="margin: 0; color: #666;">IMEI: ${item.device.deviceNumber || "N/A"}</p>
        <p style="margin: 4px 0 0 0; color: #666;">速度: ${item.locus.speed || "0"}km/h</p>
        <p style="margin: 4px 0 0 0; color: #666;">定位时间: ${item.device.lastTime || "0"}( ${item.locus.orientation || "暂无"})</p>
        <p style="margin: 4px 0 0 0; color: #666;">电源: ${item.locus.battery == "开" ? "开启" : "关闭"}km/h</p>
        <p style="margin: 4px 0 0 0; color: #666;">总里程: ${item.locus.mileage || "0"}km</p>
      </div>`,
      { width: 300, height: 220 }
    );
    const infoWindow2 = new (window as any).BMapGL.InfoWindow(
      `<div style="padding: 10px;">
        <div style="display: flex; align-items: center; margin-bottom: 8px;">
          <h4 style="margin: 0; color: #333;">${item.carNumber || "设备"}</h4>
          <p style="margin: 0 0 0 8px; color: #B22222;">${item.locus.stayDuration}</p>
        </div>
        <p style="margin: 0; color: #666;">IMEI: ${item.deviceNumber || "N/A"}</p>
        <p style="margin: 4px 0 0 0; color: #666;">速度: ${item.locus.speed || "0"}km/h</p>
        <p style="margin: 4px 0 0 0; color: #666;">定位时间: ${item.locus.createTime || "0"}( ${item.locus.orientation || "暂无"})</p>
        <p style="margin: 4px 0 0 0; color: #666;">电源: ${item.locus.battery == "开" ? "开启" : "关闭"}</p>
        <p style="margin: 4px 0 0 0; color: #666;">总里程: ${item.locus.mileage || "0"}km</p>
      </div>`,
      { width: 300, height: 220 }
    );

    // 为标注点添加点击事件监听器
    marker.addEventListener("click", () => {
      console.log("1111", item);

      if (item.device.useStatus == 0) {
        map.openInfoWindow(infoWindow, point);
      } else if (item.device.useStatus == 1 && item.locus?.stay == "行驶") {
        map.openInfoWindow(infoWindow1, point);
      } else if (item.device.useStatus == 1 && item.locus?.stay == "停留") {
        map.openInfoWindow(infoWindow2, point);
      }
    });

    // 默认显示信息窗口
    if (item.device.useStatus == 0) {
      map.openInfoWindow(infoWindow, point);
    } else if (item.device.useStatus == 1 && item.locus?.stay == "行驶") {
      map.openInfoWindow(infoWindow1, point);
    } else if (item.device.useStatus == 1 && item.locus?.stay == "停留") {
      map.openInfoWindow(infoWindow2, point);
    }
  }
}

// 批量添加设备标注
// const createDeviceMarkers = () => {
//   if (!devList.value || devList.value.length === 0) return;

//   devList.value.forEach((device: any) => {
//     if (device.locus?.lng && device.locus?.lat) {
//       // 使用new URL方式引用图片
//       // const iconUrl = deviceIcon

//       createCustomMarker(
//         parseFloat(device.locus.lng),
//         parseFloat(device.locus.lat),
//         // iconUrl,
//         device.deviceName || '设备',
//         `设备编号: ${device.deviceCode || 'N/A'}\n状态: ${device.useStatus === 1 ? '在线' : '离线'}`
//       );
//     }
//   });
// };
onMounted(() => {
  getCustomerList();
  getDevList();

  // 初始化百度地图
  if (typeof (window as any).BMapGL !== "undefined") {
    initBaiduMap();
  } else {
    // 如果百度地图API还未加载完成，等待加载
    const checkBMap = setInterval(() => {
      if (typeof (window as any).BMapGL !== "undefined") {
        clearInterval(checkBMap);
        initBaiduMap();
      }
    }, 100);
  }
});
</script>

<style lang="scss" scoped>
.j_box1 {
  background-color: #fff;
  height: 100%;

  .device-layout {
    display: flex;
    height: 100%;
  }

  .cheBox {
    background-color: #fff;
    width: 100%;
    height: 100%;
    padding: 10px;
    border-radius: 5px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  }

  .cheBoxSelect {
    background-color: rgba(48, 96, 255, 0.1);
    border: 1px solid #3060ff;
    width: 100%;
    height: 100%;
    padding: 10px;
    border-radius: 5px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  }

  .tree-container {
    width: 280px;
    background: #f8f9fa;
    // border-radius: 8px;
    padding: 15px;
    border: 1px solid #e9ecef;
    display: flex;
    flex-direction: column;
    height: 100%;

    .tree-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;
      padding-bottom: 10px;
      border-bottom: 1px solid #e9ecef;
      flex-shrink: 0;

      h3 {
        margin: 0;
        font-size: 16px;
        font-weight: 600;
        color: #3060ff;
      }
    }

    .device-tree {
      flex: 1;
      overflow-y: auto;
      overflow-x: hidden;
      // max-height: calc(100% - 200px);
      padding-right: 5px;

      // 隐藏滚动条但保持滚动功能
      scrollbar-width: none;
      /* Firefox */
      -ms-overflow-style: none;
      /* IE and Edge */

      &::-webkit-scrollbar {
        display: none;
        /* Chrome, Safari and Opera */
      }

      :deep(.el-tree-node__content) {
        height: 28px;
        border-radius: 6px;
        margin-bottom: 2px;
        transition: all 0.3s ease;

        &:hover {
          height: 28px;
          background-color: rgba(48, 96, 255, 0.1);
        }
      }

      :deep(.el-tree-node.is-current > .el-tree-node__content) {
        background-color: #3060ff;
        color: white;
        height: 36px;

        .tree-count {
          color: rgba(255, 255, 255, 0.8);
        }

        // 添加选中状态下图标颜色为白色
        .tree-icon {
          color: white !important;
        }
      }

      .tree-node {
        display: flex;
        align-items: center;
        width: 100%;
        padding-right: 10px;

        .tree-icon {
          margin-right: 8px;
          font-size: 14px;
          color: #409eff; // 添加默认颜色
        }

        .tree-label {
          flex: 1;
          font-size: 14px;
        }

        .tree-count {
          font-size: 12px;
          color: #999;
          margin-left: 3px;
        }
      }
    }
  }

  .content-container {
    position: relative;
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    // padding: 15px;
    background: #fff;
    .djs {
      display: flex;
      align-items: center;
      position: absolute;
      z-index: 9999;
      padding: 5px 15px;
      background-color: #fff;
      border-radius: 10px;
      top: 50px;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
      left: 100px;
    }
    .posBox {
      position: absolute;
      // top: 15px;
      z-index: 999;
      width: 70%;
      margin-left: 15%;
      background-color: #fff;
      text-align: center;
      padding: 8px;
      border-bottom-left-radius: 25px;
      border-bottom-right-radius: 25px;
      box-shadow:
        0 6px 12px -4px rgba(0, 0, 0, 0.12),
        6px 0 12px -4px rgba(0, 0, 0, 0.08),
        -6px 0 12px -4px rgba(0, 0, 0, 0.08);
    }
    .baidu-map {
      width: 100%;
      height: 100%;
      // border-radius: 8px;
      border: 1px solid #e9ecef;
      min-height: 400px;
    }
  }

  .dev-list {
    width: 300px;
    background: #f8f9fa;
    border: 1px solid #e9ecef;
    display: flex;
    flex-direction: column;
    height: 100%;
  }
}
</style>
